import { useState, useEffect } from "react"
import styled from "@emotion/styled"
import { motion, AnimatePresence } from "motion/react"
import dayjs from "dayjs"
import Svg from "@/components/base/Svg"

// 类型定义
interface CheckInDay {
    date: dayjs.Dayjs
    isCheckedIn: boolean
    points: number
}

interface CheckInCalendarProps {
    onCheckIn: () => void
    checkedInDays: dayjs.Dayjs[]
    currentStreak: number
}

// 样式组件
const CalendarContainer = styled.div`
    width: 100%;
    background-color: #f2f3f5;
    border-radius: 8rem;
    padding: 12rem;
    padding-bottom: 4rem;
    margin-bottom: 16rem;
    display: flex;
    flex-direction: column;
    gap: 12rem;
`

const StreakHeader = styled.div`
    display: flex;
    align-items: flex-end;
    gap: 8rem;
`

const StreakIcon = styled.div`
    width: 24rem;
    height: 24rem;
    background-color: #f0f0f0;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
`

const StreakText = styled.div`
    font-family: Gilroy;
    font-weight: 700;
    font-size: 16rem;
`

const StreakCount = styled.div`
    color: #ff1f57;
    font-weight: bold;
    font-family: Gilroy;
    font-weight: 500;
    font-size: 18rem;
`

const StreakInfo = styled.div`
    font-family: Gilroy;
    font-weight: 700;
    font-size: 16rem;
    color: #131416;
`

const PointsText = styled.span`
    font-family: Gilroy;
    font-weight: 500;
    color: #ff1f57;
`

const MonthSelector = styled.div`
    display: flex;
    justify-content: space-between;
    align-items: center;
`

const MonthButton = styled.button`
    background: none;
    border: none;
    font-size: 16rem;
    cursor: pointer;
    padding: 4rem 8rem;
`

const MonthTitle = styled.div`
    font-size: 16rem;
    font-weight: 500;
`

const WeekdayHeader = styled.div`
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    gap: 8rem;
    border-bottom: 1px solid #1c1e2126;
    height: 44rem;
`

const Weekday = styled.div`
    font-family: Gilroy;
    text-align: center;
    font-size: 14rem;
    color: ${(props) => props.color || "#40444F"};
    padding: 4rem 0;
    width: 40rem;
`

const CalendarGrid = styled.div`
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    gap: 8rem;
`

const DayCell = styled.div<{
    isCurrentMonth: boolean
    isCheckedIn: boolean
    isCurrentCheckedDay: boolean
}>`
    width: 40rem;
    height: 52rem;
    border-radius: 4rem;
    background-color: ${({ isCheckedIn, isCurrentCheckedDay }) =>
        isCurrentCheckedDay ? "#FAFAFA" : isCheckedIn ? "#ffebf0" : "#dfe0e1"};
    border: ${({ isCheckedIn, isCurrentCheckedDay }) =>
        isCheckedIn || isCurrentCheckedDay ? "1px solid #FF1F57" : "none"};
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    opacity: ${(props) => (props.isCurrentMonth ? 1 : 0.5)};
`

const DayIcon = styled.div<{ isCheckedIn: boolean }>`
    width: 24rem;
    height: 24rem;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 4rem;
    color: white;
    font-size: 12rem;

    img {
        width: 24rem;
        height: 24rem;
        object-fit: fill;
    }
`

const DayPoints = styled.div<{ isCheckedIn: boolean }>`
    font-size: 10rem;
    color: ${(props) => (props.isCheckedIn ? "#FF1F57" : "#131416")};
`

const DayDate = styled.div`
    font-family: Gilroy;
    font-size: 12rem;
    color: #69728c;
    margin-top: 4rem;
    text-align: center;
`

const CheckInButton = styled.button`
    width: 100%;
    padding: 12rem 0;
    border: none;
    border-radius: 6rem;
    background: linear-gradient(90deg, #ff3568 10%, #ff33cc 100%);
    color: white;
    font-size: 16rem;
    font-weight: bold;
    cursor: pointer;
    margin-top: 16rem;
`

const ToggleButton = styled.button`
    width: 100%;
    background: none;
    border: none;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
`

const ToggleIcon = styled(motion.div)`
    width: 24rem;
    height: 24rem;
    display: flex;
    align-items: center;
    justify-content: center;
`

const Today = styled.span`
    font-family: Gilroy;
    font-weight: 700;
    font-size: 12rem;
    line-height: 16rem;
    text-align: center;
    color: #131416;
`

// 组件实现
const CheckInCalendar: React.FC<CheckInCalendarProps> = ({
    onCheckIn,
    checkedInDays,
    currentStreak,
}) => {
    const [currentMonth, setCurrentMonth] = useState(dayjs())
    const [expanded, setExpanded] = useState(false)
    const [calendarDays, setCalendarDays] = useState<CheckInDay[]>([])
    const [recentDays, setRecentDays] = useState<CheckInDay[]>([])
    const [currentCheckedDay, setCurrentCheckedDay] = useState<dayjs.Dayjs>()

    // 生成日历数据
    useEffect(() => {
        const monthStart = currentMonth.startOf("month")
        const monthEnd = currentMonth.endOf("month")

        const days: CheckInDay[] = []
        let currentDate = monthStart

        while (currentDate.isBefore(monthEnd) || currentDate.isSame(monthEnd, "day")) {
            const isCheckedIn = checkedInDays.some(
                (checkedDate) =>
                    checkedDate.date() === currentDate.date() &&
                    checkedDate.month() === currentDate.month() &&
                    checkedDate.year() === currentDate.year(),
            )

            days.push({
                date: currentDate,
                isCheckedIn,
                points: isCheckedIn
                    ? 0
                    : currentDate.date() <= 5
                      ? 10 + currentDate.date() * 10
                      : 70,
            })

            currentDate = currentDate.add(1, "day")
        }

        setCalendarDays(days)

        // 生成最近7天的数据
        const today = dayjs()
        const recentDaysArray: CheckInDay[] = []

        for (let i = 0; i < 7; i++) {
            const date = today.add(i, "day")
            const isCheckedIn = checkedInDays.some(
                (checkedDate) =>
                    checkedDate.date() === date.date() &&
                    checkedDate.month() === date.month() &&
                    checkedDate.year() === date.year(),
            )

            recentDaysArray.push({
                date,
                isCheckedIn,
                points: isCheckedIn ? 0 : 500 + i * 100,
            })
        }

        setRecentDays(recentDaysArray)
    }, [currentMonth, checkedInDays])

    const nextMonth = () => {
        setCurrentMonth(currentMonth.add(1, "month"))
    }

    const prevMonth = () => {
        setCurrentMonth(currentMonth.subtract(1, "month"))
    }

    const toggleExpanded = () => {
        setExpanded(!expanded)
    }

    // 获取当前月的第一天是星期几，用于计算偏移
    const getMonthStartOffset = () => {
        return currentMonth.startOf("month").day()
    }

    return (
        <CalendarContainer>
            <StreakHeader>
                <StreakIcon>
                    <Svg src="pages/PointsPage/date1.svg" />
                </StreakIcon>
                <StreakCount>{currentStreak}</StreakCount>
                <StreakText>Day streak</StreakText>
            </StreakHeader>

            <StreakInfo>
                Check in for 14 days get <PointsText>22,500</PointsText> points
            </StreakInfo>

            {expanded && (
                <>
                    <MonthSelector>
                        <MonthButton onClick={prevMonth}>
                            <Svg src="pages/PointsPage/left.svg" />
                        </MonthButton>
                        <MonthTitle>{currentMonth.format("MMM YYYY")}</MonthTitle>
                        <MonthButton onClick={nextMonth}>
                            <Svg src="pages/PointsPage/right.svg" />
                        </MonthButton>
                    </MonthSelector>

                    <WeekdayHeader>
                        <Weekday color="#FF1F57">Sun</Weekday>
                        <Weekday>Mon</Weekday>
                        <Weekday>Tue</Weekday>
                        <Weekday>Wed</Weekday>
                        <Weekday>Thu</Weekday>
                        <Weekday>Fri</Weekday>
                        <Weekday color="#FF1F57">Sat</Weekday>
                    </WeekdayHeader>
                </>
            )}

            <AnimatePresence>
                {expanded ? (
                    <CalendarGrid>
                        {/* 添加空白单元格以对齐日历 */}
                        {Array.from({ length: getMonthStartOffset() }).map((_, index) => (
                            <div key={`empty-${index}`} />
                        ))}

                        {calendarDays.map((day, index) => (
                            <div key={index}>
                                <DayCell
                                    isCurrentMonth={true}
                                    isCheckedIn={day.isCheckedIn}
                                    isCurrentCheckedDay={currentCheckedDay === day.date}
                                    onClick={() => {
                                        setCurrentCheckedDay(day.date)
                                    }}
                                >
                                    <DayIcon isCheckedIn={day.isCheckedIn}>
                                        {day.isCheckedIn ? (
                                            <Svg src="pages/PointsPage/red_check.svg" />
                                        ) : (
                                            <Svg src="pages/PointsPage/coin.svg" />
                                        )}
                                    </DayIcon>
                                    <DayPoints isCheckedIn={day.isCheckedIn}>
                                        {day.points}
                                    </DayPoints>
                                </DayCell>
                                <DayDate>
                                    {day.date.isSame(dayjs(), "day") ? (
                                        <Today>Today</Today>
                                    ) : (
                                        day.date.format("D MMM")
                                    )}
                                </DayDate>
                            </div>
                        ))}
                    </CalendarGrid>
                ) : (
                    <CalendarGrid>
                        {recentDays.map((day, index) => (
                            <div key={index}>
                                <DayCell
                                    isCurrentMonth={true}
                                    isCheckedIn={day.isCheckedIn}
                                    isCurrentCheckedDay={currentCheckedDay === day.date}
                                    onClick={() => {
                                        setCurrentCheckedDay(day.date)
                                    }}
                                >
                                    <DayIcon isCheckedIn={day.isCheckedIn}>
                                        {day.isCheckedIn ? (
                                            <Svg src="pages/PointsPage/red_check.svg" />
                                        ) : (
                                            <Svg src="pages/PointsPage/coin.svg" />
                                        )}
                                    </DayIcon>
                                    <DayPoints isCheckedIn={day.isCheckedIn}>
                                        {day.points}
                                    </DayPoints>
                                </DayCell>
                                <DayDate>
                                    {day.date.isSame(dayjs(), "day") ? (
                                        <Today>Today</Today>
                                    ) : (
                                        day.date.format("D MMM")
                                    )}
                                </DayDate>
                            </div>
                        ))}
                    </CalendarGrid>
                )}
            </AnimatePresence>

            <CheckInButton onClick={onCheckIn}>Check in and get 500 points</CheckInButton>

            <ToggleButton onClick={toggleExpanded}>
                <ToggleIcon
                    animate={{ rotate: expanded ? 180 : 0 }}
                    transition={{ duration: 0.3 }}
                >
                    <Svg src="pages/PointsPage/down.svg" />
                </ToggleIcon>
            </ToggleButton>
        </CalendarContainer>
    )
}

export default CheckInCalendar
